package util;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class FileUtils {
    public static String readText(String path){

        File f = new File(path);
        if (!f.exists()){
            return "";
        }

        FileInputStream in = null;
        BufferedReader reader = null;
        StringBuilder content = new StringBuilder();
        try{
            in = new FileInputStream(f);
            reader = new BufferedReader(new InputStreamReader(in,StandardCharsets.UTF_8));
            String line = "";
            while ((line = reader.readLine())!= null){
                content.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            close(reader);
            close(in);
        }
        return content.toString();
    }

    public static void writeText(String path,String msg){
        File file = new File(path);

        create(path);

        try {
            try (FileOutputStream output = new FileOutputStream(file)) {
               output.write(msg.getBytes(StandardCharsets.UTF_8));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void close(Closeable obj){
        if (obj != null){
            try {
                obj.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void create(String path){
        File f = new File(path);

        File p = f.getParentFile();
        if (!p.exists()){
            p.mkdirs();
        }

        if (!f.exists()){
            try {
                f.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
